package org.JWCB.system.utils;

import com.alibaba.cloud.commons.lang.StringUtils;
import org.JWCB.common.core.enums.ResultCode;
import org.JWCB.common.core.exception.ServiceException;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

public class FileValidationUtils {


    private static final long maxImageSize = 5 * 1024 * 1024;

    private static final List<String> allowedExtensions = Arrays.asList("jpg", "jpeg", "png", "gif");
    public static void imageFileValid(MultipartFile file) throws IOException {
        if (file == null || file.isEmpty() || StringUtils.isEmpty(file.getOriginalFilename()) || file.getInputStream().available() == 0) {
            throw new ServiceException(ResultCode.FILE_EMPTY);
        }
        if(!validImageType(file)) {
            throw new ServiceException(ResultCode.IMAGE_FILE_TYPE_ERROR);
        }
        if(!validImageSize(file.getBytes().length)) {
            throw new ServiceException(ResultCode.FILE_TOO_BIG);
        }
    }


    private static String getExtension(String originalFilename) {
        return originalFilename.substring(originalFilename.lastIndexOf('.')+1).toLowerCase();
    }


    private static boolean validImageType(MultipartFile file) {
        return allowedExtensions.contains(getExtension(Objects.requireNonNull(file.getOriginalFilename())))
                &&  file.getContentType() != null && file.getContentType().startsWith("image/");
    }


    private static boolean validImageSize(long size) {
        return size <= maxImageSize;
    }
}
